package org.related.config;

import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.context.annotation.DeferredImportSelector;
import org.springframework.core.GenericTypeResolver;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * @Package org.releated.config
 * @PROJECT_NAME: question
 * @DESCRIPTION:
 * @USER: zhuchenglin
 * @DATE: 2022/3/1 11:27
 */
public abstract class MySpringFactoryImportSelector<T> implements DeferredImportSelector, BeanClassLoaderAware {

    private Class<?> annotationClass;

    private ClassLoader beanClassLoader;

    public MySpringFactoryImportSelector() {
        // 获取泛型类
        this.annotationClass = GenericTypeResolver.resolveTypeArgument(this.getClass(), MySpringFactoryImportSelector.class);
    }

    @Override
    public String[] selectImports(AnnotationMetadata metadata) {
        // 获取泛型类的属性
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(
                metadata.getAnnotationAttributes(this.annotationClass.getName(), true));

        Assert.notNull(attributes, "No " + getSimpleName() + " attributes found. Is "
                + metadata.getClassName() + " annotated with @" + getSimpleName() + "?");

        // 根据泛型类的全限类名加载spring.factories
        List<String> factories = new ArrayList<>(new LinkedHashSet<>(SpringFactoriesLoader
                .loadFactoryNames(this.annotationClass, this.beanClassLoader)));
        // 返回加载后的类包装的String数组
        return factories.toArray(new String[factories.size()]);
    }

    protected String getSimpleName() {
        return this.annotationClass.getSimpleName();
    }

    @Override
    public void setBeanClassLoader(ClassLoader beanClassLoader) {
        this.beanClassLoader = beanClassLoader;
    }
}
